<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <!-- 搜索添加-->
      <el-row :gutter="20">
        <el-col :span="7">
          <el-input placeholder="请输入" v-model="queryInfo.query" clearable @clear="getUserList()">
            <el-button slot="append" icon="el-icon-search" @click="getUserList()"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="addDialogVisible = true">添加用户</el-button>
        </el-col>
      </el-row>

      <!--表格-->
      <el-table :data="userList" border stripe>
        <el-table-column
          fixed
          prop="account"
          label="账号"
          width="120">
        </el-table-column>
        <el-table-column
          prop="mobile"
          label="电话"
          width="120">
        </el-table-column>
        <el-table-column
          prop="roleName"
          label="角色"
          width="120">
        </el-table-column>
        <el-table-column
          prop="lasttime"
          label="最近登录">
        </el-table-column>
        <el-table-column
          prop="last_ip"
          label="最后一次IP">
        </el-table-column>
        <el-table-column
          prop="login"
          label="登录次数"
          width="80">
        </el-table-column>

        <el-table-column
          label="状态"
          width="100">
          <template slot-scope="scope">
            <el-switch
              @change="userStareChange(scope.row)"
              :active-value=1
              :inactive-value=2
              v-model="scope.row.status"
              active-color="#13ce66"
              inactive-color="#ff4949">
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column
          fixed="right"
          label="操作">
          <template slot-scope="scope">
            <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDialog(scope.row.aid)"></el-button>
            <el-button type="danger" icon="el-icon-delete" size="mini"
                       @click="removeUserById(scope.row.aid)"></el-button>

            <el-tooltip class="item" effect="dark" content="权限分配" placement="top" :enterable="false">
              <el-button type="warning" icon="el-icon-setting" size="mini" @click="setRole(scope.row)"></el-button>
            </el-tooltip>

          </template>
        </el-table-column>
      </el-table>

      <!--分页-->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[10, 1, 2, 3, 5]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>

      <!--添加用户-->
      <el-dialog
        title="添加用户"
        :visible.sync="addDialogVisible"
        @close="addDialogClose"
        width="50%">

        <!--内容操作-->
        <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="100px">
          <el-form-item label="用户账号" prop="account">
            <el-input v-model="addForm.account"></el-input>
          </el-form-item>

          <el-form-item label="密码" prop="password">
            <el-input v-model="addForm.password"></el-input>
          </el-form-item>

          <el-form-item label="手机" prop="mobile">
            <el-input v-model="addForm.mobile"></el-input>
          </el-form-item>

        </el-form>

        <span slot="footer" class="dialog-footer">
    <el-button @click="addDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="addUser">确 定</el-button>
  </span>
      </el-dialog>

      <!--修改用户-->
      <el-dialog
        title="修改用户"
        :visible.sync="editDialogVisible"
        @close="editDialogClose"
        width="50%">

        <!--内容操作-->
        <el-form  ref="editFormRef" label-width="100px">
          <el-form-item label="用户名称" prop="username">
            <el-input v-model="editForm.account" disabled></el-input>
          </el-form-item>

          <el-form-item label="手机" prop="mobile">
            <el-input v-model="editForm.mobile"></el-input>
          </el-form-item>

          <el-form-item label="密码" prop="password">
            <el-input v-model="editForm.password" placeholder='不修改留空'></el-input>
          </el-form-item>

        </el-form>

        <span slot="footer" class="dialog-footer">
    <el-button @click="editDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="editUser()">确 定</el-button>
  </span>
      </el-dialog>

      <!--权限操作-->
      <el-dialog
        title="权限分配"
        :visible.sync="roleUserdialogVisible"
        width="50%">
        <div>
          <p>当前用户: {{userinfo.account}}</p>
          <p>当前角色: {{userinfo.roleName}}</p>
          <p>分配新角色:
            <el-select v-model="selectRoleId" placeholder="请选择">
              <el-option
                v-for="item in roleList"
                :key="item.rid"
                :label="item.name"
                :value="item.rid">
              </el-option>
            </el-select>
          </p>

        </div>
        <span slot="footer" class="dialog-footer">
    <el-button @click="roleUserdialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="saveRoleInfo()">确 定</el-button>
  </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
export default {
  data () {
    return {
      queryInfo: {
        query: '',
        page: 1, // 页数
        limit: 10 // 条数
      },
      roles: [],
      userList: [],
      total: 0,
      addDialogVisible: false,
      editDialogVisible: false,
      // 添加用户
      addForm: {
        username: '',
        password: ''
      },
      // 修改用户
      editForm: {
        username: ''
      },
      addFormRules: {
        username: [
          {
            required: true,
            message: '请输入用户名',
            trigger: 'blur'
          },
          {
            min: 6,
            max: 15,
            message: '长度在 6 到 15 个字符',
            trigger: 'blur'
          }
        ],
        password: [
          {
            required: true,
            message: '请输入用户密码',
            trigger: 'blur'
          },
          {
            min: 6,
            max: 15,
            message: '长度在 6 到 15 个字符',
            trigger: 'blur'
          }
        ]
      },
      userinfo: {},
      roleList: {},
      selectRoleId: '',
      roleUserdialogVisible: false // 分配权限
    }
  },
  created () {
    this.getUserList()
  },
  methods: {
    async getUserList () {
      const { data: res } = await this.$http.post('Admin/admins', this.queryInfo)
      if (res.code !== 1000) return this.$message.error(res.msg)
      this.userList = res.data.list
      this.total = res.data.count
    },

    // 每页多少条
    handleSizeChange (pageNum) {
      this.queryInfo.page = 1
      this.queryInfo.limit = pageNum
      this.getUserList()
    },
    // 到第几页
    handleCurrentChange (pageChange) {
      this.queryInfo.page = pageChange
      this.getUserList()
    },
    // 状态修改
    async userStareChange (data) {
      // `users/${data.id}/state/${data.mg_state}`
      console.log(data)
      const { data: res } = await this.$http.post('Admin/setAdminStatus', data)
      if (res.code !== 1000) return this.$message.error(res.msg)
      this.$message.success(res.msg)
    },

    // 监听对话框关闭
    addDialogClose () {
      this.$refs.addFormRef.resetFields()
    },
    // 添加用户
    addUser () {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return false
        const { data: res } = await this.$http.post('Admin/addAdmin', this.addForm)
        console.log(res)
        if (res.code !== 1000) {
          this.$message.error(res.msg)
        } else {
          this.$message.success(res.msg)
          this.addDialogVisible = false
          this.getUserList()
        }
      })
    },
    // 展示编辑
    async showEditDialog (id) {
      const { data: res } = await this.$http.post('Admin/getAdminInfo', { aid: id })
      if (res.code !== 1000) return this.$message.error(res.msg)
      this.editForm = res.data
      this.editDialogVisible = true
    },
    // 修改用户信息
    async editUser () {
        const { data: res } = await this.$http.post('Admin/editAdmin', this.editForm)
        console.log(res)
        if (res.code !== 1000) {
          this.$message.error(res.msg)
        } else {
          this.$message.success(res.msg)
          this.editDialogVisible = false
          this.getUserList()
        }
    },
    // 监听修改框关闭
    editDialogClose () {
      this.$refs.editFormRef.resetFields()
    },
    // 删除用户操作
    async removeUserById (id) {
      console.log(id)
      // 弹窗
      const confirmResult = await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(msg => {
        return msg
      }).catch(err => {
        return err
      })

      if (confirmResult !== 'confirm') {
        return this.$message({
          type: 'info',
          message: '已取消删除'
        })
      }

      const { data: res } = await this.$http.post('Admin/delAdmin', { aid: id })
      if (res.code !== 1000) {
        this.$message.error(res.msg)
      } else {
        this.$message.success(res.msg)
        this.getUserList()
      }
    },
    // 分配权限操作
    async setRole (row) {
      this.userinfo = row
      console.log(row)
      // 获取权限列表
      const { data: res } = await this.$http.get('Admin/getRole')
      if (res.code !== 1000) return this.$message.error(res.msg)
      this.roleList = res.data
      this.roleUserdialogVisible = true
    },
    // 保存新分配的角色
    async saveRoleInfo () {
      if (!this.selectRoleId) return this.$message.error('请先选择角色')
      const { data: res } = await this.$http.post('Admin/saveAdminRole', { aid: this.userinfo.aid, rid: this.selectRoleId })
      if (res.code !== 1000) return this.$message.error(res.msg)
      this.$message.success(res.msg)
      this.selectRoleId = ''
      this.roleUserdialogVisible = false
      this.getUserList()
    }
  }

}
</script>
<style lang="less" scoped>
.el-table {
  margin: 12px;
  font-size: 12px;
}
</style>
